package com.qx.cn.tool;

import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

public class UploadConfigurationRead
{
    private static String PFILE = "upload.properties";
    
    private URI uri = null;
    
    private long m_lastModifiedTime = 0L;
    
    private File m_file = null;
    
    private Properties m_props = null;
    
    private static UploadConfigurationRead m_instance = new UploadConfigurationRead();
    
    private UploadConfigurationRead()
    {
        try
        {
            this.m_lastModifiedTime = getFile().lastModified();
            if (this.m_lastModifiedTime == 0L)
            {
                System.err.println(PFILE + "file does not exist!");
            }
            this.m_props = new Properties();
            this.m_props.load(new FileInputStream(getFile()));
        }
        catch (URISyntaxException e)
        {
            System.err.println(PFILE + "文件路径不正确");
            e.printStackTrace();
        }
        catch (Exception e)
        {
            System.err.println(PFILE + "文件读取异常");
            e.printStackTrace();
        }
    }
    
    private File getFile()
        throws URISyntaxException
    {
        URI fileUri = getClass().getClassLoader().getResource(PFILE).toURI();
        this.m_file = new File(fileUri);
        return this.m_file;
    }
    
    public static synchronized UploadConfigurationRead getInstance()
    {
        return m_instance;
    }
    
    public String getConfigItem(String name, String defaultVal)
    {
        long newTime = this.m_file.lastModified();
        
        if (newTime == 0L)
        {
            if (this.m_lastModifiedTime == 0L)
            {
                System.err.println(PFILE + " file does not exist!");
            }
            else
            {
                System.err.println(PFILE + " file was deleted!!");
            }
            return defaultVal;
        }
        if (newTime > this.m_lastModifiedTime)
        {
            this.m_props.clear();
            try
            {
                this.m_props.load(new FileInputStream(getFile()));
            }
            catch (Exception e)
            {
                System.err.println("文件重新读取异常");
                e.printStackTrace();
            }
        }
        this.m_lastModifiedTime = newTime;
        String val = this.m_props.getProperty(name);
        if (val == null)
        {
            return defaultVal;
        }
        return val;
    }
    
    public String getConfigItem(String name)
    {
        return getConfigItem(name, "");
    }
}